package com.jiepos.mpos.biz.review.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.biz.appInfM.service.MessageInfService;
import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.AppCustomerInfoDao;
import com.jiepos.mpos.common.dao.CustomAccountChangeDao;
import com.jiepos.mpos.common.dao.MemReviewDao;
import com.jiepos.mpos.common.dao.MenuDao;
import com.jiepos.mpos.common.entity.App_Custom_InfEntity;
import com.jiepos.mpos.common.entity.App_Menu_CdEntity;
import com.jiepos.mpos.common.entity.MemReviewEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.CollectionUtil;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * @ClassName: MemReviewService
 * @Description: 审核管理服务层
 * @author 张磊
 * @date 2017年9月21日 下午3:08:25
 */
@Service
public class MemReviewService extends BaseService{

	private static final Logger _log = LoggerFactory.getLogger(MemReviewService.class);
	@Autowired
	private MemReviewDao memReviewDao;
	
	@Autowired
	private AppCustomerInfoDao appCustomerInfoDao;
	
	@Autowired
	private MenuDao menuDao;
	
	@Autowired
	private CustomAccountChangeDao customAccountChangeDao;
	
	@Autowired
	private MessageInfService messageInfService;
	
	/**
	 * 查询实名认证待办事项列表json分页数据
	 * @param pagination 分页对象
	 * @param request
	 * @param memReviewEntity 实名认证实体对象
	 * @return
	 */
	public Map getMemReviewList(Pagination pagination, HttpServletRequest request,MemReviewEntity memReviewEntity){
		StringBuffer sb = new StringBuffer();
		sb.append("select aa.* from (");
		sb.append("SELECT t1.CUSTOM_UUID, t1.CUSTOM_UUID as uuid,t1.CUSTOM_NO,CONCAT(RPAD (SUBSTR (t1.PHONE, 1, 3),LENGTH (t1.PHONE) - 4,'*'),SUBSTR (t1.PHONE,LENGTH (t1.PHONE) - 3,4)) phone,t1.NAME,");
		sb.append(" CONCAT(RPAD (SUBSTR (t2.login_id, 1, 3),LENGTH (t2.login_id) - 4,'*'),SUBSTR (t2.login_id,LENGTH (t2.login_id) - 3,4))||'-'||t2.NAME SUPCUSTOM,");
		sb.append("t3.ins_uuid,t3.ins_cd,t3.ins_cn_nm,NVL2(t3.ins_cd,t3.ins_cd||'-'||t3.ins_cn_nm,'') insname,NVL2(t4.area_cd,t4.area_cd||'-'|| t4.area_cn_nm, '') areaname,t1.REALNAME_AUTH_ST,t1.REALNAME_AUDIT_ST,t1.REC_ST,");
		sb.append(" CONCAT (RPAD (SUBSTR (t1.CERTIFICATE_NO, 1, 6),LENGTH (t1.CERTIFICATE_NO) - 4,'*'),SUBSTR (t1.CERTIFICATE_NO,LENGTH (t1.CERTIFICATE_NO) - 3,4)) AS \"CERTIFICATE_NO\",");
		sb.append("to_char(t1.rec_crt_ts,'yyyy-mm-dd hh24:mi:ss') as rec_crt_ts,");
		sb.append("to_char(t1.rec_upd_ts,'yyyy-mm-dd hh24:mi:ss') as rec_upd_ts,t1.rec_upd_usr_id from ");
		sb.append(Table.T_APP_CUSTOM_INF );
		sb.append(" t1 left join ");
		sb.append(Table.T_APP_CUSTOM_INF );
		sb.append(" t2 on t1.SUP_CUSTOM_UUID = t2.CUSTOM_UUID left join ");
		sb.append(Table.T_APP_INS_INF );
		sb.append(" t3 ON t1.ins_uuid = t3.ins_uuid left join ");
		sb.append(Table.T_APP_AREA_CD );
		sb.append(" t4 on t1.area_uuid = t4.area_uuid where 1=1 ");
		sb.append(" and  t1.rec_st ! = ? and t1.realname_audit_st in (");
		sb.append( SystemConstant.REVIEW_ST_0).append(") ) aa ");
		sb.append(" where 1=1 ");
		List list = new ArrayList();
		list.add(SystemConstant.REC_ST_0);
		if (!StringUtils.isBlank(memReviewEntity.getCustom_no())) {
			sb.append( " and custom_no like ? " );
			list.add("%" + memReviewEntity.getCustom_no() + "%");
		}
		if (!StringUtils.isBlank(memReviewEntity.getPhone())) {
			sb.append( " and phone like ? " );
			list.add("%" + memReviewEntity.getPhone() + "%");
		}
		if (!StringUtils.isBlank(memReviewEntity.getName())) {
			sb.append( " and name like ? " );
			list.add("%" + memReviewEntity.getName() + "%");
		}
		if (!StringUtils.isBlank(memReviewEntity.getIns_cd())) {
			sb.append( " and ins_cd like ? " );
			list.add("%" + memReviewEntity.getIns_cd() + "%");
		}
		if (!StringUtils.isBlank(memReviewEntity.getIns_cn_nm())) {
			sb.append( " and ins_cn_nm like ? " );
			list.add("%" + memReviewEntity.getIns_cn_nm() + "%");
		}
		if (!StringUtils.isBlank(memReviewEntity.getCertificate_no())) {
			sb.append( " and certificate_no like ? " );
			list.add("%" + memReviewEntity.getCertificate_no() + "%");
		}
		pagination.queryString = sb.toString();
		pagination = super.getCustomAuthSql(request, pagination, "aa", null);
		pagination.queryString = pagination.queryString+" and aa.rec_st != '0' order by aa.rec_upd_ts desc ";
		return memReviewDao.getPaginationMap(pagination, "aa", list);
	}
	
	/**
	 * 审核通过操作
	 */
	public void memReviewPass(String audit_comments,String custom_uuid,String bankcard_uuid, Map map){
		/*调用审核*/
		boolean isSuccess = memReviewDao.reviewCustomer(audit_comments, custom_uuid, bankcard_uuid, map, true);
		if(isSuccess){
			//调用存储过程 新增会员佣金分润记录
			Map<String, String> paramMap = new HashMap<>();
			paramMap.put("i_amount_type", "1");
			paramMap.put("custom_uuid", custom_uuid);
			paramMap.put("loc_trace_no", null);
			this.customAccountChange(paramMap);
		}
	}
	
	
	/**
	 * 退回修改
	 * @param audit_comments
	 * @param custom_uuid
	 * @param map
	 */
	@SuppressWarnings("unchecked")
	public void memReviewBack(String audit_comments,String custom_uuid,Map map){
		memReviewDao.reviewCustomer(audit_comments, custom_uuid, null, map, false);
	}
	
	/**
	 * 获取待办事项数量
	 * @return
	 */
	public Integer getMemberReviewNum(HttpServletRequest request){
		
		StringBuilder sb = new StringBuilder();
		List<String> list = new ArrayList<>();
		sb.append("select custom_uuid from ");
		sb.append(Table.T_APP_CUSTOM_INF);
		sb.append(" where realname_audit_st = ? and rec_st != ? and ins_uuid in (");
		sb.append(" select tt.ins_uuid from "+Table.T_APP_INS_INF+" tt ");
		sb.append(" start with tt.ins_uuid = ?");
		sb.append(" connect by prior tt.ins_uuid = tt.sup_ins_uuid )");
		list.add(SystemConstant.REVIEW_ST_0);
		list.add(SystemConstant.REC_ST_0);
		list.add(String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_INS_UUID)));
		List<String> result = memReviewDao.queryForList(sb.toString(),list);
		if (CollectionUtil.isEmpty(result)) {
	         return 0;
	    } else {
	         return result.size();
	    }
	}
	
	/**
	 * 获取相应的code对象
	 * @param menuUrl
	 * @return
	 */
	public App_Menu_CdEntity getMenuCode(String menuUrl){
		
		if(!StringUtils.isEmpty(menuUrl)){
			return menuDao.findByParam("menu_url", menuUrl);
		}else {
			return null;
		}
	}
	
	/**
	 * 校验用户是否已审核
	 * @param custom_uuid
	 * @return
	 */
	public String checkCustomInfo(String custom_uuid, String bankcard_uuid) {

		// 判断用户是否已审核
		String param1[] = { "custom_uuid", "realname_audit_st", "rec_st" };
		String param2[] = { custom_uuid, SystemConstant.REVIEW_ST_0, SystemConstant.REC_ST_1 };
		App_Custom_InfEntity app_Custom_InfEntity = appCustomerInfoDao.findByParamses(param1, param2);

		if (app_Custom_InfEntity == null) {
			return SystemConstant.ERROR;
		}
		// 判断卡号是否重复
		/*boolean saved = false;
		App_Custom_BankcardEntity app_Custom_BankcardEntity = appCustomBankCardDao.findByParam("bankcard_uuid",
				bankcard_uuid);
		if (app_Custom_BankcardEntity != null) {
			saved = appCustomBankcardService.alreadySaveCardInfo(app_Custom_BankcardEntity.getCertificate_no(),
					app_Custom_BankcardEntity.getSettle_acct(), SystemConstant.ACCT_ATTR_0);
		}
		if(saved){
			return "f2";
		}*/

		return SystemConstant.SUCCESS;

	}
	
	/**
	 * 计算推荐佣金和推送
	 * @param map
	 */
	public void customAccountChange(Map<String,String> map){
		try{
			Map<String,String> pushMap=customAccountChangeDao.insertCustomAccChange(map.get("i_amount_type"), map.get("custom_uuid"), map.get("loc_trace_no"));
			_log.info("计算佣金返回map=[{}]", pushMap);
			//消息推送
			if(pushMap!=null&&!pushMap.isEmpty()){			
				String o_direct_custom_uuid=pushMap.get("o_direct_custom_uuid");
				String o_indirect_custom_uuid=pushMap.get("o_indirect_custom_uuid");
				String o_direct_amount=pushMap.get("o_direct_amount");
				String o_indirect_amount=pushMap.get("o_indirect_amount");
				String title="用户推荐佣金到账通知";
				StringBuffer textDirect=new StringBuffer();
				String phone = pushMap.get("o_custom_phone");
				phone = StringUtils.hideData("2", phone);
				if(!StringUtils.isBlank(o_direct_amount) && Double.parseDouble(o_direct_amount) != 0.00){
					textDirect.append("用户").append(phone).append("已通过实名认证,");
					textDirect.append("您获得了").append(o_direct_amount).append("元").append("推荐佣金").append("！");
					if(!StringUtils.isBlank(o_direct_custom_uuid)){
						messageInfService.pushMessage(o_direct_custom_uuid, null, title, textDirect.toString());				
					}
				}
				
				if(!StringUtils.isBlank(o_indirect_amount) && Double.parseDouble(o_indirect_amount) != 0.00){
					StringBuffer textIndirect=new StringBuffer();
					textIndirect.append("用户").append(phone).append("已通过实名认证,");
					textIndirect.append("您获得了").append(o_indirect_amount).append("元").append("推荐佣金").append("！");
					if(!StringUtils.isBlank(o_indirect_custom_uuid)){
						messageInfService.pushMessage(o_indirect_custom_uuid, null, title, textIndirect.toString());				
					}
				}
			
						
				
									
			}
		}catch(Exception e){
			_log.error("计算佣金和推送发生异常",e);	
		}
	}
	
}
